package com.xiaoxiong.gobang.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import com.xiaoxiong.gobang.R;
import com.xiaoxiong.gobang.ai.FirstAi;
import com.xiaoxiong.gobang.ai.ThirdAi;
import com.xiaoxiong.gobang.bean.ComputerPlayer;
import com.xiaoxiong.gobang.bean.GameState;
import com.xiaoxiong.gobang.bean.HumanPlayer;
import com.xiaoxiong.gobang.bean.Player;
import com.xiaoxiong.gobang.control.GameControl;
import com.xiaoxiong.gobang.control.PutChessControl;
import com.xiaoxiong.gobang.evaluate.FirstEvaluate;

/**
 * @author xiaoxiong
 * @Package com.xiaoxiong.gobang.ui
 * @Description:
 * @email 249900679@qq.com
 * @date 2016/4/3 9:28
 */
public class GameActivity extends BaseActivity implements View.OnTouchListener, GameViewInterface {

    private ComputerPlayer[] computerPlayer;
    private HumanPlayer[] humanPlayers;
    private int howManyHuman;
    private int howManyComputer;
    private PutChessControl putChessControl;
    private GameControl gameControl;
    private GameState gameState;
    private GameView2 gameView;
    private TextView back;
    private TextView firstname;
    private TextView secondname;
    private TextView textTv;
    private TextView countTv1;
    private TextView countTv2;
    private TextView startTv;
    private int[] m_board;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.game_layout);
        gameView = (GameView2) findViewById(R.id.game);
        back = (TextView) findViewById(R.id.back);
        firstname = (TextView) findViewById(R.id.name1);
        secondname = (TextView) findViewById(R.id.name2);
        textTv = (TextView) findViewById(R.id.textv);
        countTv1 = (TextView) findViewById(R.id.count1);
        countTv2 = (TextView) findViewById(R.id.count2);
        startTv = (TextView) findViewById(R.id.start);
        gameView.setOnTouchListener(this);
        gameView.invalidate();

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!gameControl.isOver()) {
                    Log.d("over", gameControl.isOver() + "");
                    new AlertDialog.Builder(GameActivity.this).setTitle("还未结束，确认退出吗？")
                            .setIcon(android.R.drawable.ic_dialog_info)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    gameControl.Stop();
                                    GameActivity.this.finish();
                                }
                            })
                            .setNegativeButton("返回", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            }).show();
                }else{
                    GameActivity.this.finish();
                }
            }
        });

        computerPlayer = new ComputerPlayer[2];
        humanPlayers = new HumanPlayer[2];
        howManyHuman = 0;
        howManyComputer = 0;
        this.m_board = new int[15*15+34+15];
        for(int i = 0;i < 15;++i){
            for(int j = 0;j < 15;++j){
                m_board[17+i+j*16] = -1;
            }
        }

        Init();
    }

    private void Init() {

        gameControl = new GameControl();

        Intent in = this.getIntent();
        int dep = in.getIntExtra("playerdepth1", 0);
        if (dep > 0 && dep < 3) {
            computerPlayer[howManyComputer] = new ComputerPlayer(in.getStringExtra("playername1"));
            gameControl.setPlayers(computerPlayer[howManyComputer], Player.FIRSTPLAYER);
            computerPlayer[howManyComputer++].SetSearcher(new ThirdAi(), dep);
        } else {
            humanPlayers[howManyHuman] = new HumanPlayer(in.getStringExtra("playername1"));
            gameControl.setPlayers(humanPlayers[howManyHuman++], Player.FIRSTPLAYER);
//            textTv.setText(in.getStringExtra("playername1") + "下棋中...");
        }
        dep = in.getIntExtra("playerdepth2", 0);
        if (dep > 0 && dep < 3) {
            computerPlayer[howManyComputer] = new ComputerPlayer(in.getStringExtra("playername2"));
            gameControl.setPlayers(computerPlayer[howManyComputer], Player.SECONDPLAYER);
            computerPlayer[howManyComputer++].SetSearcher(new ThirdAi(), dep);
        } else {
            humanPlayers[howManyHuman] = new HumanPlayer(in.getStringExtra("playername2"));
            gameControl.setPlayers(humanPlayers[howManyHuman++], Player.SECONDPLAYER);
        }

        firstname.setText(in.getStringExtra("playername1"));
        secondname.setText(in.getStringExtra("playername2"));

        gameState = new GameState();
        gameState.InitGameState(Player.FIRSTPLAYER);
        gameState.set_evaluator(new FirstEvaluate());

        putChessControl = new PutChessControl();
        putChessControl.setGameState(gameState);
        putChessControl.setGameViewInterface(this);

        gameControl.setChessPosition(putChessControl);
        Log.d("game", gameState.toString());
        gameControl.InitGameState(gameState);

        startTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startTv.setVisibility(View.GONE);
                textTv.setText(firstname.getText() + "下棋中...");
                gameControl.Run();
            }
        });
    }

    private Handler mHandler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            Bundle bundle = msg.getData();
            String name = bundle.getString("name");
            if (name.equals(firstname.getText().toString())) {
                int c = Integer.parseInt(countTv1.getText().toString());
                countTv1.setText((c + 1) + "");
                textTv.setText(secondname.getText() + "下棋中...");
            } else if (name.equals(secondname.getText().toString())) {
                int c = Integer.parseInt(countTv2.getText().toString());
                countTv2.setText((c + 1) + "");
                textTv.setText(firstname.getText() + "下棋中...");
            }
        }
    };
    private Handler mHandler2 = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            gameView.setBoard(m_board);
        }
    };

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        switch (event.getAction()) {
            case MotionEvent.ACTION_UP:
                int pos = gameView.getPos(event.getX(), event.getY());
                Log.d("human",howManyHuman + "个人,位置" + pos);
                if (pos < 256 && m_board[pos] == Player.NULLPALYER) {
                    for (int i = 0; i < howManyHuman; ++i) {
                        Log.d("human","点击了");
                        humanPlayers[i].setPos(pos);
                    }
                }
                break;
            default:
                break;
        }

        return true;
    }
    @Override
    public void setText(String name) {
        Message message = new Message();
        Bundle bundle = new Bundle();
        bundle.putCharSequence("name", name);
        message.setData(bundle);
        mHandler.sendMessage(message);
    }

    @Override
    public void putChess(int[] board) {
        m_board = board;
        mHandler2.sendEmptyMessage(1);
    }

    @Override
    public void GameOver(String winnerName) {
        Message message = new Message();
        Bundle bundle = new Bundle();
        bundle.putCharSequence("winner", winnerName);
        message.setData(bundle);
        gameOverHandle.sendMessage(message);
    }

    private Handler gameOverHandle = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            Bundle bundle = msg.getData();
            String winnerName = bundle.getString("winner");
            if(winnerName == null){
                winnerName = "和棋";
            }else{
                winnerName += "赢!";
            }
            textTv.setText(winnerName);
            new AlertDialog.Builder(GameActivity.this).setTitle("游戏结束\n" + winnerName)
                    .setIcon(android.R.drawable.ic_dialog_info)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            startTv.setVisibility(View.GONE);
                            gameControl.Stop();
                        }
                    }).show();
        }
    };
}
